import {
  getOderAddressApi,
  getOderApi,
  getBuyApi,
  postOrderApi,
  OrderStatusApi,
  WechatPayApi
} from '../../../api/orderPay'
import { toast } from '@/utils/extendApi'
const app = getApp()
import { formatTime } from '../../../utils/formatTime'
import Schema from '../../async-validator/index'

// 防抖
import { debounce } from 'miniprogram-licia'
Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '', // 期望送达日期
    blessing: '', // 祝福语
    orderAddress: {},
    orderInfo: {},
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    currentDate: new Date().getTime()
  },

  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },
  validatorPerson(params) {
    // 验证订购人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'

    // 验证手机号，是否符合中国大陆手机号码的格式
    const phoneRegExp =
      '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      userAddressId: [{ required: true, message: '请选择收货地址' }],
      buyName: [
        { required: true, message: '请输入订购人姓名' },
        {
          pattern: nameRegExp,
          message: '订购人姓名不合法'
        }
      ],
      buyPhone: [
        { required: true, message: '请选择订购人手机号' },
        {
          pattern: phoneRegExp,
          message: '订购人手机号不合法'
        }
      ],
      deliveryDate: [{ required: true, message: '请选择送达日期' }]
    }
    const validator = new Schema(rules)
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          toast({ title: errors[0].message })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },
  submitOrder: debounce(async function () {
    const {
      buyName,
      buyPhone,
      deliveryDate,
      blessing,
      orderAddress,
      orderInfo
    } = this.data
    const params = {
      buyName,
      buyPhone,
      cartList: orderInfo.cartVoList,
      deliveryDate,
      remarks: blessing,
      userAddressId: orderAddress.id
    }
    const { valid } = await this.validatorPerson(params)
    // console.log(valid)
    if (!valid) return
    const res = await postOrderApi(params)
    // console.log(res)
    if (res.code === 200) {
      this.orderNo = res.data
      this.advancePay()
    }
  }, 500),
  async advancePay() {
    const res = await WechatPayApi(this.orderNo)
    if (res.code === 200) {
      // console.log(res.data)
      try {
        const payInfo = await wx.requestPayment(res.data)
        // console.log(payInfo)
        if (payInfo.errMsg === 'requestPayment:ok') {
          const payStatus = await OrderStatusApi(this.orderNo)
          if (payStatus.code === 200) {
            wx.redirectTo({
              url: '/modules/orderPayModule/pages/order/list/list',
              success: () => {
                wx.toast({
                  title: '支付成功',
                  icon: 'success'
                })
              }
            })
          }
        }
      } catch (error) {
        wx.toast({ title: '支付失败,请联系客服', icon: 'error' })
      }
    }
  },
  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    const { detail } = event
    // console.log(detail)
    const timeRes = formatTime(new Date(detail))
    // console.log(timeRes)
    this.setData({
      show: false,
      deliveryDate: timeRes
    })
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/settingModule/pages/address/list/index'
    })
  },
  async getOrderDetail() {
    const { goodsId, blessing } = this.data
    const { data: orderInfo } = goodsId
      ? await getBuyApi(goodsId, blessing)
      : await getOderApi()
    // console.log(orderInfo)
    const orderGoods = orderInfo.cartVoList.find((item) => item.blessing !== '')
    this.setData({
      orderInfo,
      blessing: !orderGoods ? '' : orderGoods.blessing
    })
  },
  async getOderAddress() {
    const res = await getOderAddressApi()
    // console.log(res)
    const addressId = app.globalData.address.id
    if (addressId) {
      this.setData({
        orderAddress: app.globalData.address
      })
      return
    }
    const { data: orderAddress } = res
    this.setData({
      orderAddress
    })
  },
  onLoad(options) {
    if (options.goodsId) {
      this.setData({
        ...options
      })
    }
  },
  onShow() {
    this.getOderAddress()
    this.getOrderDetail()
  },
  onUnload() {
    app.globalData.address = {}
  }
})
